﻿

用户列表
@*添加按钮*@
<div>
    <button type="button" id="add" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUser">添加 </button>
</div>

@*表格*@
<table id="userTable" class="table table-hover table-sm fs-6">
    <thead>
        <tr>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

@*添加对话框*@
<div class="modal fade" id="addUser" tabindex="-1" data-bs-backdrop="static" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">添加用户</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <label for="recipient-name" class="col-form-label">用户名:</label>
                        <input type="text" class="form-control" id="userName">
                        <label for="recipient-name" class="col-form-label">密码:</label>
                        <input type="password" class="form-control" id="password">
                        <label for="recipient-name" class="col-form-label">角色:</label>
                        <select id="roleId" class="form-select" aria-label="">
                            <option value="0">请选择</option>
                        </select>
                        <label for="recipient-name" class="col-form-label">真名:</label>
                        <input type="text" class="form-control" id="realName">
                        <label for="recipient-name" class="col-form-label">电话:</label>
                        <input type="text" class="form-control" id="phone">
                        <label for="recipient-name" class="col-form-label">QQ:</label>
                        <input type="text" class="form-control" id="qq">
                        <label for="recipient-name" class="col-form-label">科目:</label>
                        <select id="subjectId" class="form-select" aria-label="">
                            <option value="0">请选择</option>
                        </select>
                        <label for="recipient-name" class="col-form-label">部门:</label>
                        <select id="departmentId" class="form-select" aria-label="">
                            <option value="0">请选择</option>
                        </select>
                        <label for="recipient-name" class="col-form-label">办公室:</label>
                        <select id="officeRoomId" class="form-select" aria-label="">
                            <option value="0">请选择</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="submitAdd">保存</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>


@*编辑对话框*@
<div class="modal fade" id="editUser" tabindex="-1" data-bs-backdrop="static" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">编辑用户</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <label for="recipient-name" class="col-form-label">用户id:</label>
                    <input type="text" class="form-control" id="newUserId">
                    <label for="recipient-name" class="col-form-label">用户名:</label>
                    <input type="text" class="form-control" id="newUserName">
                    <label for="recipient-name" class="col-form-label">密码:</label>
                    <input type="text" class="form-control" id="newPassword">
                    <label for="recipient-name" class="col-form-label">角色:</label>
                    <select id="newRoleId" class="form-select" aria-label="">
                        <option value="0">请选择</option>
                    </select>
                    <label for="recipient-name" class="col-form-label">真名:</label>
                    <input type="text" class="form-control" id="newRealName">
                    <label for="recipient-name" class="col-form-label">电话:</label>
                    <input type="text" class="form-control" id="newPhone">
                    <label for="recipient-name" class="col-form-label">QQ:</label>
                    <input type="text" class="form-control" id="newqq">
                    <label for="recipient-name" class="col-form-label">科目:</label>
                    <select id="newSubjectId" class="form-select" aria-label="">
                        <option value="0">请选择</option>
                    </select>
                    <label for="recipient-name" class="col-form-label">部门:</label>
                    <select id="newDepartmentId" class="form-select" aria-label="">
                        <option value="0">请选择</option>
                    </select>
                    <label for="recipient-name" class="col-form-label">办公室:</label>
                    <select id="newOfficeRoomId" class="form-select" aria-label="">
                        <option value="0">请选择</option>
                    </select>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="submitEdit">保存</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>



@*确定删除对话框*@
<div class="modal fade" id="sureDel" tabindex="-1" data-bs-backdrop="static" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">删除部门</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确认删除吗?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="submitDel">确定</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <script>
        let g_rows
        let deplist
        let rolelist
        let subjectlist
        let officelist

        loadpage()
        getSelectData()
        function loadpage() {
            
            let s = sessionStorage.getItem('userlist')
            if (s == [] || s == "" || s == null) {
                $.ajax({
                    url: '/User/GetUserList',
                    type: 'get',
                    success: function (data) {
                        parseData(data)
                    },
                    error: function (err) {
                    }
                })
            } else {
                parseStorage(s)
            }
        }


        //解析ajax请求返回数据并加载到表格
        function parseData(data) {
            $('#userTable thead tr').empty()
            $('#userTable tbody tr').empty()
            let jsd = JSON.stringify(data)

            let head = JSON.parse(data.attr)
            head.push('操作')
            sessionStorage.setItem('userlist_head', JSON.stringify(head))

            //渲染表头
            for (index in head) {
                $('#userTable thead tr').append('<th>' + head[index] + '</th>')
            }

            let rows = JSON.parse(data.row)
            g_rows = rows
            sessionStorage.setItem('userlist', JSON.stringify(rows))

            //渲染表格
            $(rows).each(function (index, ele) {
                $('#userTable tbody').append('<tr></tr>')
                for (key in ele) {
                    $('#userTable tbody tr:last').append('<td>' + ele[key] + '</>')
                }
                $('#userTable tbody tr:last').append('<td>' +
                    '<button class="editBtn" onclick="edit(this)" data-bs-toggle="modal" data-bs-target="#editUser">编辑</button>' +
                    '<button class="delBtn" onclick="del(this)" data-bs-toggle="modal" data-bs-target="#sureDel">删除</button>' +
                    '</td>')
                $('#userTable tbody tr td:last').attr({ 'userId': ele.UserId })
            })
            $('.delBtn').addClass("btn btn-danger btn-sm")
            $('.editBtn').addClass("btn btn-primary btn-sm")
        }



        //解析缓存并加载到表格
        function parseStorage(data) {
            $('#userTable thead tr').empty()
            $('#userTable tbody tr').empty()
            let headStorage = sessionStorage.getItem('userlist_head')
            let head = JSON.parse(headStorage)
            //渲染表头
            for (index in head) {
                $('#userTable thead tr').append('<th>' + head[index] + '</th>')
            }

            //渲染表格
            let rows = JSON.parse(data)
            $(rows).each(function (index, ele) {
                $('#userTable tbody').append('<tr></tr>')
                for (key in ele) {
                    $('#userTable tbody tr:last').append('<td>' + ele[key] + '</>')
                }
                $('#userTable tbody tr:last').append('<td>' +
                    '<button class="editBtn" data-bs-toggle="modal" data-bs-target="#editUser">编辑</button>' +
                    '<button class="delBtn" data-bs-toggle="modal" data-bs-target="#sureDel">删除</button>' +
                    '</td>')
                $('#userTable tbody tr td:last').attr({ 'userId': ele.UserId })

            })
            $('.delBtn').addClass("btn btn-danger btn-sm")
            $('.editBtn').addClass("btn btn-primary btn-sm")
        }


        //刷新数据
        function refreshData() {
            $('#userTable thead tr').empty()
            $('#userTable tbody tr').empty()
            $.ajax({
                url: '/User/GetUserList',
                type: 'get',
                success: function (data) {
                    parseData(data)
                },
                error: function (err) {
                }
            })
        }


        

        //获取下拉框数据
        function getSelectData() {
            let roleStor = JSON.parse(sessionStorage.getItem('rolelist'))
            let depStor = JSON.parse(sessionStorage.getItem('deplist'))
            let subjectStor = JSON.parse(sessionStorage.getItem('subjectlist'))
            let officeStor = JSON.parse(sessionStorage.getItem('officelist'))
            if (roleStor == null || depStor == null || subjectStor == null || officeStor==null) {
                initSelectData()
            }
            else {
                rolelist = roleStor
                deplist = depStor
                subjectlist = subjectStor
                officelist = officeStor
            }

        }

        //初始化下拉框数据 存缓存
        function initSelectData() {
            $.ajax({
                url: '/Role/GetRoleList',
                type: 'get',
                success: function (data) {
                    sessionStorage.setItem('rolelist', data.row)
                    let head = JSON.parse(data.attr)
                    head.push('操作')
                    sessionStorage.setItem('rolelist_head', JSON.stringify(head))
                    rolelist = JSON.parse(data["row"])
                },
                error: function (err) {
                }
            })
            $.ajax({
                url: '/Department/GetDepList',
                type: 'get',
                success: function (data) {
                    sessionStorage.setItem('deplist', data.row)

                    let head = JSON.parse(data.attr)
                    head.push('操作')
                    sessionStorage.setItem('deplist_head', JSON.stringify(head))
                    deplist = JSON.parse(data['row'])
                },
                error: function (err) {
                }
            })

            $.ajax({
                url: '/Subject/GetSubjectList',
                type: 'get',
                success: function (data) {
                    sessionStorage.setItem('subjectlist', data.row)
                    let head = JSON.parse(data.attr)
                    head.push('操作')
                    sessionStorage.setItem('subjectlist_head', JSON.stringify(head))
                    subjectlist = JSON.parse(data['row'])
                },
                error: function (err) {
                }
            })

            $.ajax({
                url: '/OfficeRoom/GetOfficeRoomList',
                type: 'get',
                success: function (data) {
                    sessionStorage.setItem('officelist', data.row)
                    let head = JSON.parse(data.attr)
                    head.push('操作')
                    sessionStorage.setItem('officelist_head', JSON.stringify(head))
                    officelist = JSON.parse(data['row'])
                },
                error: function (err) {
                }
            })

        }

        //渲染"添加"中下拉框
        function rendSelects() {
            $('#roleId').empty()
            $('#roleId').append("<option value='0'>请选择</option>")
            $(rolelist).each(function (index, ele) {
                $('#roleId').append("<option value=''></option>")
                $('#roleId option:last').val(ele.RoleId)
                $('#roleId option:last').text(ele.RoleName)
            })

            $('#subjectId').empty()
            $('#subjectId').append("<option value='0'>请选择</option>")
            $(subjectlist).each(function (index, ele) {
                $('#subjectId').append("<option value=''></option>")
                $('#subjectId option:last').val(ele.SubjectId)
                $('#subjectId option:last').text(ele.SubjectName)
            })

            $('#departmentId').empty()
            $('#departmentId').append("<option value='0'>请选择</option>")
            $(deplist).each(function (index, ele) {
                $('#departmentId').append("<option value=''></option>")
                $('#departmentId option:last').val(ele.DepartmentId)
                $('#departmentId option:last').text(ele.DepName)
            })

            $('#officeRoomId').empty()
            $('#officeRoomId').append("<option value='0'>请选择</option>")
            $(officelist).each(function (index, ele) {
                $('#officeRoomId').append("<option value=''></option>")
                $('#officeRoomId option:last').val(ele.OfficeRoomId)
                $('#officeRoomId option:last').text(ele.OfficeRoomName)
            })
        }

        $('#add').click(function(){
            rendSelects()
        })


        //提交添加
        $('#submitAdd').click(function(){
            let userName = $('#userName').val()
            let password = $('#password').val()
            let roleId = $('#roleId').val()
            let realName = $('#realName').val()
            let phone = $('#phone').val()
            let qq = $('#qq').val()
            let subjectId = $('#subjectId').val()
            let departmentId = $('#departmentId').val()
            let officeRoomId = $('#officeRoomId').val()
            $.ajax({
                url: '/User/AddUser',
                type: 'post',
                data:{
                    UserName:userName,
                    Password:password,
                    RoleId:roleId,
                    RealName:realName,
                    Phone:phone,
                    QQ:qq,
                    SubjectId:subjectId,
                    DepartmentId:departmentId,
                    OfficeRoomId: officeRoomId
                },
                success: function (data) {
                    if(data==1){
                        alert('添加成功')
                    }
                    if (data == 0) {
                        alert('角色、科目、必填!')
                    }
                    refreshData()
                },
                error: function (err) {
                }
            })
        })

        //渲染"编辑"中的下拉框
        function rendNewSelects() {
            $('#newRoleId').empty()
            $('#newRoleId').append("<option value='0'>请选择</option>")
            $(rolelist).each(function (index, ele) {
                $('#newRoleId').append("<option value=''></option>")
                $('#newRoleId option:last').val(ele.RoleId)
                $('#newRoleId option:last').text(ele.RoleName)
            })

            $('#newSubjectId').empty()
            $('#newSubjectId').append("<option value='0'>请选择</option>")
            $(subjectlist).each(function (index, ele) {
                $('#newSubjectId').append("<option value=''></option>")
                $('#newSubjectId option:last').val(ele.SubjectId)
                $('#newSubjectId option:last').text(ele.SubjectName)
            })

            $('#newDepartmentId').empty()
            $('#newDepartmentId').append("<option value='0'>请选择</option>")
            $(deplist).each(function (index, ele) {
                $('#newDepartmentId').append("<option value=''></option>")
                $('#newDepartmentId option:last').val(ele.DepartmentId)
                $('#newDepartmentId option:last').text(ele.DepName)
            })

            $('#newOfficeRoomId').empty()
            $('#newOfficeRoomId').append("<option value='0'>请选择</option>")
            $(officelist).each(function (index, ele) {
                $('#newOfficeRoomId').append("<option value=''></option>")
                $('#newOfficeRoomId option:last').val(ele.OfficeRoomId)
                $('#newOfficeRoomId option:last').text(ele.OfficeRoomName)
            })
        }


        //第一次加载页面--“编辑”按钮响应事件
        function edit(e) {
            rendNewSelects()
            let userId = $(e).parent().attr('userid')
            let user = g_rows.filter(function (u) {
                return u.UserId == userId
            })
            console.log(user)
            $('#newUserId').val(user[0].UserId)
            $('#newUserId').attr({ 'disabled': 'disabled' })

            $('#newUserName').val(user[0].UserName)
            $('#newPassword').val(user[0].Password)
            $('#newRoleId').val(user[0].RoleId)
            $('#newRealName').val(user[0].RealName)
            $('#newPhone').val(user[0].Phone)
            $('#newqq').val(user[0].QQ)
            $('#newSubjectId').val(user[0].SubjectId)
            $('#newDepartmentId').val(user[0].DepartmentId)
            $('#newOfficeRoomId').val(user[0].OfficeRoomId)
        }

        //使用缓存--“编辑”按钮响应事件
        $('.editBtn').each(function (index) {
            $(this).click(function () {
                rendNewSelects()
                let rows = JSON.parse(sessionStorage.getItem('userlist'))
                let user = rows.filter(function (r, ind) {
                    return index == ind
                })
                $('#newUserId').val(user[0].UserId)
                console.log()
                $('#newUserId').attr({ 'disabled': 'disabled' })

                $('#newUserName').val(user[0].UserName)
                $('#newPassword').val(user[0].Password)
                $('#newRoleId').val(user[0].RoleId)
                $('#newRealName').val(user[0].RealName)
                $('#newPhone').val(user[0].Phone)
                $('#newqq').val(user[0].QQ)
                $('#newSubjectId').val(user[0].SubjectId)
                $('#newDepartmentId').val(user[0].DepartmentId)
                $('#newOfficeRoomId').val(user[0].OfficeRoomId)
            })
        })

        //编辑对话框中的“保存”按钮点击事件响应
        $('#submitEdit').click(function (index) {
            let userId = $('#newUserId').val()
            let userName = $('#newUserName').val()
            let password = $('#newPassword').val()
            let roleId = $('#newRoleId').val()
            let realName = $('#newRealName').val()
            let phone = $('#newPhone').val()
            let qq= $('#newqq').val()
            let subjectId = $('#newSubjectId').val()
            let depId = $('#newDepartmentId').val()
            let officeRoomId = $('#newOfficeRoomId').val()
            if (roleId <= 0 || subjectId <= 0 || depId <= 0 || officeRoomId<=0) {
               return
            }

            if (userName == '' || password == null ) {
                //提示名称不能为空

                return
            }

            $.ajax({
                url: '/User/EditUser',
                type: 'post',
                data: {
                    UserId: userId,
                    UserName: userName,
                    Password: password,
                    RoleId: roleId,
                    RealName: realName,
                    Phone: phone,
                    QQ:qq,
                    SubjectId: subjectId,
                    DepartmentId: depId,
                    OfficeRoomId: officeRoomId
                },
                success: function (data) {
                    if (data == 1) {
                        alert("修改成功")
                    }
                    else if (data == 0) {
                        alert('用户名已存在!')
                    } else if (data == -1) {
                        alert('用户和密码不能为空!')
                    }
                    //刷新表格
                    refreshData()
                    //关闭对话框
                    // ...
                },
                error: {

                }
            })
        })




        //第一次加载页面--"删除"按钮响应事件
        let userId
        function del(e) {
            userId = $(e).parent().attr('userid')
        }


        //缓存的数据--"删除"按钮点击事件响应
        $('.delBtn').each(function (index) {
            $(this).click(function () {
                let stor = sessionStorage.getItem('userlist')

                let rows = JSON.parse(stor)
                let tr = $(rows).filter(function (ind, ele) {
                    return ind == index
                })
                userId = tr[0].UserId
            })
        })


        //"删除"对话框--"确定"按钮响应事件
        $('#submitDel').click(function () {
            let delId=userId
            if (delId <= 0) {
                return
            }

            $.ajax({
                url: '/User/DelUser',
                type: 'post',
                data: {
                    UserId: delId
                },
                success: function (data) {
                    if (data == 1) {
                        alert("删除成功")
                    }
                    else {
                        alert('删除失败!')
                    }
                    //刷新表格
                    refreshData()
                    //关闭对话框
                    // ...
                },
                error: {

                }
            })
        })
    </script>

}